import threading
import config
import time
from logger import logger
from PySide6 import QtWidgets
from PySide6.QtGui import QAction, QIcon
from utils.task import Task
from store.goods import Goods
from store.goods_sync import GoodsSync
from .main_table import MainTableWidget
from .main_config import MainConfigDialog

class MainWidget(QtWidgets.QMainWindow):
    def __init__(self, app):
        super().__init__()
        self.app = app
        self.resize(1000, 700)

        self.label = self.statusBar()
        
        self.menu = self.menuBar()
        menu_action = self.menu.addMenu("操作")
        action_config = QAction("配置", self)
        action_config.triggered.connect(self.config_dialog)
        menu_action.addAction(action_config)
        action_empty = QAction("清空同步缓存", self)
        action_empty.triggered.connect(self.goods_sync_empty)
        menu_action.addAction(action_empty)
        
        self.table = MainTableWidget(self)
        self.setCentralWidget(self.table)
        
        self.goods = Goods()
        self.goods_sync = GoodsSync()
        self.timer = None
    
    def show(self):
        super().show()
        self.setWindowTitle(f"Dokker 库存同步 {self.app.login.user['company_name']}({self.app.login.user['staff_name']})")
        self.get_data()

    def closeEvent(self, event):
        if self.timer is not None:
            self.timer.cancel()
        self.task.quit()
        logger.info('main widget close')
        event.accept()
    
    def config_dialog(self):
        dialog = MainConfigDialog()
        if dialog.exec() == MainConfigDialog.DialogCode.Accepted:
            # 可能 config 中更新了 wc 的 key,重新实例化一下
            self.goods_sync.woocommerce()
            self.log("已更新配置")

    def get_data(self):
        self.task = Task(self.get_goods)
        self.task.over.connect(self.over_data)
        self.task.start()
    
    def over_data(self):
        # 判断是否有错误
        if self.goods.error:
            return self.app.login_show()

        # 下次延迟执行
        self.timer = threading.Timer(int(config.read('update_time')), self.get_data)
        self.timer.start()

    def get_goods(self):
        def log_page():
            self.log(f"己加载SKU {len(self.goods.sku)} 件")

        self.log("正在加载商品")
        self.goods.reset()
        self.goods.get_all(log_page)

        # 更新表格
        self.table.update_model(self.goods.sku)
        # 准备同步
        self.sync_goods()

    def sync_goods(self):
        def log_check(index, item, count):
            self.log(f"正在核对 {item['sn']} ({index+1}/{count})")
            

        self.log("准备进行同步")
        # 延迟一下
        time.sleep(2)

        # 检查需要同步的sku
        goods = self.goods_sync.handle_goods(self.goods.sku)
        # 开始检查
        sync = self.goods_sync.check(goods, log_check)
        # 开始同步
        self.log(f"准备同步 {len(sync)} 件")
        if self.goods_sync.sync(sync) == True:
            # 更新
            self.goods_sync.update(goods)
            self.log(f"同步完成，共有SKU {len(self.goods.sku)} 件, 已同步 {len(sync)} 件")
        else:
            self.log(f"同步失败，等待下次尝试")

    def goods_sync_empty(self):
        self.goods_sync.empty()
        self.log("已清空同步缓存")
    
    def log(self, text):
        self.label.showMessage(text)
        logger.info(text)